package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.SensitiveWordUtil;
import com.heima.media.dto.ArticleDto;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmSensitive;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.ArticleFeign;
import com.heima.media.service.*;
import org.apache.commons.io.IOUtils;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Service
public class AuditServiceImpl implements IAuditService {
    /**
     * 审核
     *
     * @param wmNews
     */
    @Override
    @Async
    public void audit(WmNews wmNews) {
        System.out.println(Thread.currentThread().getName() + " 开始执行自动审核服务...");

        // 如果文章状态为8或4 4是人工审核通过
        if (wmNews.getStatus() == 4 || wmNews.getStatus() == 8) {
            if (System.currentTimeMillis() <= wmNews.getPublishTime().getTime()) {
                sendDelayMessage(wmNews);
            } else {
                saveArticle(wmNews);
            }
        }

        // 判断自媒体文章的状态,如果状态为1 进入自动审核流程
        if (wmNews.getStatus() == 1) {
            // 审核文本内容,调用阿里云文本审核
            // 提取内容中的文本内容和图片内容
            Map<String, Object> map = getTextAndImagesFromContent(wmNews.getContent());
            String text = (String) map.get("text");
            // 内容图片
            List<String> images = (List<String>) map.get("images");

            // 先进行本地敏感词库的一个匹配
            boolean sensResult = checkSens(wmNews, text);
            if (!sensResult) return;
            boolean textResult = checkText(wmNews, text);
            // 审核图片内容,调用阿里云图片审核
            if (!textResult) return;
            // 有可能封面图片跟内容图片不一样
            List<ImageDto> coverImages = JSON.parseArray(wmNews.getImages(), ImageDto.class);
            for (ImageDto image : coverImages) {
                if (!images.contains(image.getUrl())) {
                    images.add(image.getUrl());
                }
            }
            boolean imageResult = checkImage(wmNews, images);
            // 调用文章服务保存文章
            if (!imageResult) return;

            // 判断是否立刻发布文章,判断当前系统时间是否大于等于文章的发布时间
            if (System.currentTimeMillis() <= wmNews.getPublishTime().getTime()) {
                sendDelayMessage(wmNews);
            } else {
                saveArticle(wmNews);
            }


        }
    }

    private void sendDelayMessage(WmNews wmNews) {
        // 如果是未到发布时间,修改文章的状态为8 -审核通过待发布
        wmNews.setStatus(8);
        newsService.updateById(wmNews);
        // 发送延迟消息
        RBlockingQueue<Object> blockingQueue = redissonClient.getBlockingQueue("article-publish");
        RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);
        // 延迟的长度为文章发布时间 - 当前系统时间
        long time = wmNews.getPublishTime().getTime() - System.currentTimeMillis();
        delayedQueue.offer(wmNews, time, TimeUnit.MILLISECONDS);
    }

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IWmSensitiveService sensitiveService;

    /**
     * 本地敏感词过滤
     *
     * @param wmNews
     * @param text
     * @return
     */
    private boolean checkSens(WmNews wmNews, String text) {
        if (SensitiveWordUtil.dictionaryMap.size() == 0) {
            // 初始化
            // 查询所有的敏感词
            LambdaQueryWrapper<WmSensitive> query = new LambdaQueryWrapper<>();
            // select sensitives from wm_sensitive
            query.select(WmSensitive::getSensitives);
            List<String> words = sensitiveService.listObjs(query, o -> o.toString());
            SensitiveWordUtil.initMap(words);
        }
        // 审核标题+标签+内容
        Map<String, Integer> map = SensitiveWordUtil.matchWords(wmNews.getTitle() + wmNews.getLabels() + text);
        if (map.size() > 0) {
            wmNews.setStatus(2);
            Set<String> keys = map.keySet();
            String join = String.join(" ", keys);
            wmNews.setReason("敏感词审核不通过: " + join);
            newsService.updateById(wmNews);
            return false;
        }
        return true;
    }

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IWmUserService userService;

    @Autowired
    private IWmChannelService channelService;

    /**
     * 保存文章
     *
     * @param wmNews
     */
    private void saveArticle(WmNews wmNews) {
        // 调用文章服务接口
        ArticleDto dto = new ArticleDto();
        dto.setTitle(wmNews.getTitle());
        // 从 wm_user 查询作者信息
        WmUser wmUser = userService.getById(wmNews.getUserId());
        dto.setAuthorId(wmUser.getApAuthorId());
        dto.setAuthorName(wmUser.getName());
        dto.setChannelId(wmNews.getChannelId());
        // 查询频道名称
        WmChannel wmChannel = channelService.getById(wmNews.getChannelId());
        dto.setChannelName(wmChannel.getName());
        dto.setLayout(wmNews.getType());
        dto.setFlag(0);
        // 前端显示的图片是图片地址,中间已逗号分隔
        List<ImageDto> list = JSON.parseArray(wmNews.getImages(), ImageDto.class);
        List<String> images = new ArrayList<>();
        for (ImageDto imageDto : list) {
            images.add(imageDto.getUrl());
        }
        // 将集合转变成逗号分隔的字符串
        String join = String.join(",", images);
        dto.setImages(join);
        dto.setContent(wmNews.getContent());
        dto.setLabels(wmNews.getLabels());
        dto.setPublishTime(wmNews.getPublishTime());
        ResponseResult<Long> longResponseResult = articleFeign.saveArticle(dto);
        if (longResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            Long articleId = longResponseResult.getData();
            if (articleId != null) {
                // 将文章id写回到自媒体文章表中
                wmNews.setArticleId(articleId);
                // 修改文章表的状态为9
                wmNews.setStatus(9);
                newsService.updateById(wmNews);
            }

        }
    }

    @Autowired
    private MinIOService minIOService;

    /**
     * 阿里云图片审核
     *
     * @param wmNews
     * @param images
     * @return
     */
    private boolean checkImage(WmNews wmNews, List<String> images) {
        boolean result = false;
        if (images.size() == 0) {
            return true;
        }
        try {
            List<byte[]> imageList = new ArrayList<>();
            // minio服务部署在内网,需要先下载然后去阿里云审核
            for (String image : images) {
                if (!StringUtils.isEmpty(image)) {
                    InputStream inputStream = minIOService.download(image);
                    // 流转字节数组
                    byte[] bytes = IOUtils.toByteArray(inputStream);
                    imageList.add(bytes);
                }
            }
            Map map = imageScan.imageScan(imageList);
            // 判断结果
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "pass":
                    result = true;
                    break;
                case "block":
                    // 审核不通过
                    // 修改文章状态为 2
                    wmNews.setStatus(2);
                    // 记录对应的原因
                    wmNews.setReason("阿里云图片审核失败: " + map.get("label"));
                    newsService.updateById(wmNews);
                    break;
                case "review":
                    // 需要人工审核
                    // 修改文章状态为 3
                    wmNews.setStatus(3);
                    newsService.updateById(wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 提取内容中的文本内容和图片内容
     *
     * @param content
     * @return
     */
    private Map<String, Object> getTextAndImagesFromContent(String content) {
        Map<String, Object> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        List<String> images = new ArrayList<>();
        List<ContentDto> dtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto dto : dtos) {
            if (dto.getType().equals("text")) {
                // 添加到文本内容
                sb.append(dto.getValue());
            } else {
                // 添加到图片集合
                images.add(dto.getValue());
            }
        }
        map.put("text", sb.toString());
        map.put("images", images);
        return map;
    }

    @Autowired
    private GreenTextScan textScan;

    @Autowired
    private GreenImageScan imageScan;

    @Autowired
    private IWmNewsService newsService;

    /**
     * 阿里云文本审核
     *
     * @param wmNews
     * @param text
     * @return
     */
    private boolean checkText(WmNews wmNews, String text) {
        boolean result = false;
        // 需要审核的文本包含 标题+标签+文本内容
        text = wmNews.getTitle() + wmNews.getLabels() + text;
        try {
            Map map = textScan.greenTextScan(text);
            // 判断结果
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "pass":
                    result = true;
                    break;
                case "block":
                    // 审核不通过
                    // 修改文章状态为 2
                    wmNews.setStatus(2);
                    // 记录对应的原因
                    wmNews.setReason("阿里云文本审核失败: " + map.get("label"));
                    newsService.updateById(wmNews);
                    break;
                case "review":
                    // 需要人工审核
                    // 修改文章状态为 3
                    wmNews.setStatus(3);
                    newsService.updateById(wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
